package ReadWriteLock;

import org.omg.CORBA.PUBLIC_MEMBER;

import java.util.Random;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadWriteLock {
    public static void main(String[] args) {
        ReadWrite readWrite = new ReadWrite();
        for (int i = 0; i < 3; i++) {
            WriteThread write = new WriteThread(readWrite , new Random().nextInt(100));
            write.setName("写线程"+i);
            write.start();
        }
        for (int i = 0; i < 3; i++) {
            ReadThread read = new ReadThread(readWrite);;
            read.setName("读线程"+i);
            read.start();
        }
    }

    static class ReadThread extends Thread{
        private ReadWrite readWrite;
        public ReadThread(ReadWrite readWrite){
            this.readWrite = readWrite;
        }

        @Override
        public void run() {
            super.run();
            readWrite.read();
        }
    }

    static class WriteThread extends Thread{
        private ReadWrite readWrite;
        private Object object;

        public WriteThread(ReadWrite readWrite, Object object) {
            this.readWrite = readWrite;
            this.object = object;
        }

        @Override
        public void run() {
            super.run();
            readWrite.write(object);
        }
    }

    static class ReadWrite {
        private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
        private Object object = null;
        public void read(){
            try {
                lock.readLock().lock();
                System.out.println(Thread.currentThread().getName() + "开始读.");
                Thread.sleep(new Random().nextInt(100));
                System.out.println(Thread.currentThread().getName() + "读到了" + object);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.readLock().unlock();
            }
        }

        public void write(Object object){
            try{
                lock.writeLock().lock();
                this.object = object;
                System.out.println(Thread.currentThread().getName() + "开始写.");
                Thread.sleep(new Random().nextInt(100));
                System.out.println(Thread.currentThread().getName() + "写到了" + object);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.writeLock().unlock();
            }
        }
    }
}
